package com.company.huisuo.biz.activity

import android.app.Activity
import android.content.Intent
import android.widget.Toast
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.LinearSnapHelper
import androidx.recyclerview.widget.RecyclerView
import com.company.huisuo.base.BaseActivity
import com.company.huisuo.biz.adapter.GameGroupAdapter
import com.company.huisuo.biz.bean.AppGameParticipantRespVO
import com.company.huisuo.databinding.ActivityGameGroupBinding
import com.company.huisuo.repository.GameRepository
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

/**
 * 游戏组合
 */
class GameGroupActivity : BaseActivity<ActivityGameGroupBinding>() {

    private val mAdapter by lazy {
        GameGroupAdapter()
    }
    
    private val gameRepository by lazy {
        GameRepository()
    }
    
    // 游戏游玩记录ID，实际使用时需要从Intent或其他方式获取
    private var gamePlayRecordId: Long = 1024L

    companion object {
        private val STR_1 = "休息一会"
        private val STR_2 = "继续游戏"

        fun start(activity: Activity) {
            Intent(activity, GameGroupActivity::class.java).apply {
                activity.startActivity(this)
            }
        }
    }

    override fun initView() {
        mBinding.ivBack.setOnClickListener {
            finish()
        }
        mBinding.rcvList.apply {
            layoutManager =
                LinearLayoutManager(this@GameGroupActivity, RecyclerView.HORIZONTAL, false)
            adapter = mAdapter
        }
        
        // 设置删除参与人回调
        mAdapter.onDeleteClick = { participant, position ->
            deleteParticipant(participant, position)
        }
        val snap = LinearSnapHelper()
        snap.attachToRecyclerView(mBinding.rcvList)

        // 监听滚动，实时更新中央 Item 的选中状态
        mBinding.rcvList.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                super.onScrolled(recyclerView, dx, dy)
                updateCenterItemSelection(snap)
            }

            override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                super.onScrollStateChanged(recyclerView, newState)
                // 滚动停止时也更新一次，确保准确
                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                    updateCenterItemSelection(snap)
                }
            }
        })

        mBinding.ivAdd.setOnClickListener {
            AddGroupActivity.start(this, gamePlayRecordId)
        }
        mBinding.tvStart.setOnClickListener {
            finish()
        }
        mBinding.tvWait.setOnClickListener {
            if (mBinding.tvWait.text == STR_1) {
                mBinding.tvWait.text = STR_2
            } else {
                finish()
            }
        }
    }

    private fun updateCenterItemSelection(snap: LinearSnapHelper) {
        val centerView = snap.findSnapView(mBinding.rcvList.layoutManager)
        centerView?.let {
            val position = mBinding.rcvList.getChildAdapterPosition(it)
            if (position != RecyclerView.NO_POSITION && mAdapter.mSelectPos != position) {
                mAdapter.selectPos(position)
            }
        }
    }

    override fun initData() {
        // 从API获取游戏参与人列表
        lifecycleScope.launch {
            try {
                val result = gameRepository.getGameParticipantList(gamePlayRecordId)
                if (result.isSuccess) {
                    val participants = result.getOrNull()
                    if (!participants.isNullOrEmpty()) {
                        mAdapter.submitList(participants)
                    } else {
                        // 如果没有参与人，加载默认数据
                        loadDefaultParticipants()
                    }
                } else {
                    // 请求失败，加载默认数据
                    loadDefaultParticipants()
                }
            } catch (e: Exception) {
                // 异常情况，加载默认数据
                loadDefaultParticipants()
            }
            
            // 滚动到中间位置
            delay(100)
            mBinding.rcvList.smoothScrollToPosition(if (mAdapter.itemCount > 0) mAdapter.itemCount / 2 else 0)
        }
    }
    
    /**
     * 加载默认参与人数据
     */
    private fun loadDefaultParticipants() {
        val defaultParticipants = listOf(
            AppGameParticipantRespVO(
                id = 1L,
                gamePlayRecordId = gamePlayRecordId,
                customerId = 1L,
                customerName = "DJ蓝莓",
                artistId = 1L,
                artistName = "王总"
            ),
            AppGameParticipantRespVO(
                id = 2L,
                gamePlayRecordId = gamePlayRecordId,
                customerId = 2L,
                customerName = "小美",
                artistId = 2L,
                artistName = "李总"
            ),
            AppGameParticipantRespVO(
                id = 3L,
                gamePlayRecordId = gamePlayRecordId,
                customerId = 3L,
                customerName = "小芳",
                artistId = 3L,
                artistName = "张总"
            ),
            AppGameParticipantRespVO(
                id = 4L,
                gamePlayRecordId = gamePlayRecordId,
                customerId = 4L,
                customerName = "小红",
                artistId = 4L,
                artistName = "赵总"
            ),
            AppGameParticipantRespVO(
                id = 5L,
                gamePlayRecordId = gamePlayRecordId,
                customerId = 5L,
                customerName = "小丽",
                artistId = 5L,
                artistName = "刘总"
            ),
            AppGameParticipantRespVO(
                id = 6L,
                gamePlayRecordId = gamePlayRecordId,
                customerId = 6L,
                customerName = "小雪",
                artistId = 6L,
                artistName = "陈总"
            )
        )
        mAdapter.submitList(defaultParticipants)
    }
    
    /**
     * 删除参与人
     */
    private fun deleteParticipant(participant: AppGameParticipantRespVO, position: Int) {
        lifecycleScope.launch {
            try {
                val result = gameRepository.deleteGameParticipant(participant.id)
                if (result.isSuccess) {
                    // 删除成功，从列表中移除
                    val currentList = mutableListOf<AppGameParticipantRespVO>()
                    for (i in 0 until mAdapter.itemCount) {
                        mAdapter.getItem(i)?.let { currentList.add(it) }
                    }
                    currentList.removeAt(position)
                    mAdapter.submitList(currentList)
                    
                    // 如果删除的是当前选中的项目，需要更新选中位置
                    if (mAdapter.mSelectPos == position) {
                        mAdapter.mSelectPos = -1
                    } else if (mAdapter.mSelectPos > position) {
                        mAdapter.mSelectPos--
                    }
                } else {
                    // 删除失败，显示错误信息
                    Toast.makeText(this@GameGroupActivity, "删除参与人失败: ${result.exceptionOrNull()?.message}", Toast.LENGTH_SHORT).show()
                }
            } catch (e: Exception) {
                // 异常情况，显示错误信息
                Toast.makeText(this@GameGroupActivity, "删除参与人异常: ${e.message}", Toast.LENGTH_SHORT).show()
            }
        }
    }
}